package com.iotechn.unimall.admin.api.goods;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.*;
import com.iotechn.unimall.data.dto.BiaozhunCountDTO;
import com.iotechn.unimall.data.dto.goods.FileInfo;
import com.iotechn.unimall.data.dto.goods.LogDTO;
import com.iotechn.unimall.data.enums.BizType;
import com.iotechn.unimall.data.enums.SpuStatusType;
import com.iotechn.unimall.data.mapper.*;
import com.iotechn.unimall.data.model.Page;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
 import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by rize on 2019/7/11.
 */
@Service
public class AdminLogServiceImpl implements AdminLogService {


    @Autowired
    private ShopLogMapper spuMapper;
    @Autowired
    private ShopBiaozhunLogMapper  shopBiaozhunLogMapper;
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private ImgMapper imgMapper;
    @Autowired
    private ShopBiaozhunMapper shopBiaozhunMapper;

    @Autowired
    private UserShopMapper shopMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String create(LogDTO spuDTO, Long adminId) throws ServiceException {

        Date now = new Date();
        LogDO LogDO = new LogDO();
        BeanUtils.copyProperties(spuDTO, LogDO);
        LogDO.setGmtUpdate(now);
        LogDO.setGmtCreate(now);
        LogDO.setAdminId(adminId);
        if(LogDO.getGmt_day()!=null){
           LogDO.setUnit("1");//代表补的日志
        }else{
            LogDO.setGmt_day(now);
        }
        Gson gson=new Gson();
        LogDO.setFile(gson.toJson(spuDTO.getFile()));
        /*if(spuDTO.getImgList()!=null && spuDTO.getImgList().size()>0){
            String imgs = String.join(",",spuDTO.getImgList());
            LogDO.setImg(imgs);
        }*/
        LogDO.setStatus(0);

        if(spuMapper.insert(LogDO)>0){
            spuDTO.setId(LogDO.getId());
            List<ShopBiaozhunLogDO> biaozhunList=spuDTO.getBiaozhunList();
            if(biaozhunList!=null && biaozhunList.size()>0){
                for(ShopBiaozhunLogDO s:biaozhunList){
                    s.setAdminId(adminId);
                    s.setShopId(LogDO.getShopId());
                    s.setShopName(LogDO.getShopName());
                    s.setGmt_day(now);
                    s.setShop_log_id(LogDO.getId());
                    s.setType(LogDO.getType());
                    s.setFile(gson.toJson(s.getImgsList()));

                }
                shopBiaozhunLogMapper.batchInsert(biaozhunList);
            }
           }


        //插入IMG
        //insertSpuImg(spuDTO, LogDO.getId(), now);
        try{
         if(spuDTO.getType().intValue()==2) {
             jisuanjine(spuDTO);

         }
         }catch(Exception e){
             System.out.println("有异常需要处理");
        }
         return "ok";
    }
    public  float add(String doubleValA, String doubleValB) {
        BigDecimal a2 = new BigDecimal(doubleValA);
        BigDecimal b2 = new BigDecimal(doubleValB);
        return a2.add(b2).floatValue();
    }
    /**
     * 相除
     * @param doubleValA
     * @param doubleValB
     * @param scale 除不尽时指定精度
     * @return
     */
    public  float div(String doubleValA, String doubleValB, int scale) {
        BigDecimal a2 = new BigDecimal(doubleValA);
        BigDecimal b2 = new BigDecimal(doubleValB);
        return a2.divide(b2, scale, BigDecimal.ROUND_HALF_UP).floatValue();
    }
    public  float mul(String doubleValA, String doubleValB, int scale) {
        BigDecimal a2 = new BigDecimal(doubleValA);
        BigDecimal b2 = new BigDecimal(doubleValB);
        return a2.multiply(b2).setScale(scale).floatValue();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String edit(LogDTO spuDTO, Long adminId) throws ServiceException {
        if (spuDTO.getId() == null) {
            throw new AdminServiceException(ExceptionDefinition.PARAM_CHECK_FAILED);
        }

        Date now = new Date();
        LogDO logDO = new LogDO();
        BeanUtils.copyProperties(spuDTO, logDO);
        Gson gson=new Gson();
        //logDO.setFile(gson.toJson(spuDTO.getFileList()));
        if(spuDTO.getImgList()!=null && spuDTO.getImgList().size()>0){
            String imgs = String.join(",",spuDTO.getImgList());
            logDO.setImg(imgs);
        }
        logDO.setGmtUpdate(now);
        if(spuMapper.updateById(logDO)>0){
            shopBiaozhunLogMapper.batchDelete(logDO.getId());
                 List<ShopBiaozhunLogDO> biaozhunList=spuDTO.getBiaozhunList();
            if(biaozhunList!=null) {

                for (ShopBiaozhunLogDO s : biaozhunList) {
                    s.setAdminId(adminId);
                    s.setShopId(logDO.getShopId());
                    s.setShopName(logDO.getShopName());
                    s.setGmt_day(now);
                    s.setType(logDO.getType());
                    s.setShop_log_id(logDO.getId());
                    s.setFile(gson.toJson(s.getImgsList()));

                }
                shopBiaozhunLogMapper.batchInsert(biaozhunList);
            }
        }

        imgMapper.delete(new EntityWrapper<ImgDO>().eq("biz_id", logDO.getId()).eq("biz_type", BizType.LOG.getCode()));
        //插入IMG
        insertSpuImg(spuDTO, logDO.getId(), now);

        try{
            if(spuDTO.getType().intValue()==2) {
                jisuanjine(spuDTO);

            }

        }catch(Exception e){
            System.out.println("有异常需要处理");
        }
        return "ok";
    }

   public void jisuanjine(LogDTO spuDTO){
       //根据项目查询每个工程的列表；
       List<ShopBiaozhunDO> biaozhunDTOSNew = new ArrayList<>();

       List<ShopBiaozhunLogDO> biaozhunList = spuDTO.getBiaozhunList();
       /*List<Long> biaozhunIds = biaozhunList.stream().map(ShopBiaozhunLogDO::getBiaozhunId).collect(Collectors.toList());
       List<ShopBiaozhunDO> biaozhunDTOS = shopBiaozhunMapper.selectList(new EntityWrapper<ShopBiaozhunDO>()
               .in(!CollectionUtils.isEmpty(biaozhunIds), "id", biaozhunIds));
      */
       List<ShopBiaozhunDO> biaozhunDTOS = shopBiaozhunMapper.selectList(new EntityWrapper<ShopBiaozhunDO>().eq("shop_id",spuDTO.getShopId())
               .ne("gongcheng_pxuhao","0"));

       //统计到截止昨天的完成度和今天的完成度2项记录到对应的工程表里面
       List<BiaozhunCountDTO> yesterdayCountDTOS = shopBiaozhunLogMapper.getYesterdayCount(spuDTO.getShopId());
       //当是监理提交的信息时候需要重新计算每个工程的完成度和总项目的完成度
       List<BiaozhunCountDTO> todayCountDTOS=shopBiaozhunLogMapper.getTodayCount(spuDTO.getShopId());
       if (biaozhunDTOS != null && biaozhunDTOS.size() > 0) {
           for (ShopBiaozhunDO shopBiaozhunDO : biaozhunDTOS) {
               ShopBiaozhunDO shopBiaozhunDONew = new ShopBiaozhunDO();
               shopBiaozhunDONew.setId(shopBiaozhunDO.getId());
               shopBiaozhunDONew.setFinishValue(shopBiaozhunDO.getFinishValue());
               shopBiaozhunDONew.setTodayFinish(shopBiaozhunDO.getTodayFinish());
               if (shopBiaozhunDO == null || shopBiaozhunDO.getId() == null) continue;
               if (yesterdayCountDTOS != null && yesterdayCountDTOS.size() > 0) {
                   for (BiaozhunCountDTO biaozhunCountDTO : yesterdayCountDTOS) {
                       if (shopBiaozhunDO.getId().intValue() == biaozhunCountDTO.getBiaozhunId()) {
                           if (biaozhunCountDTO.getYesterdayCount() != null)
                               shopBiaozhunDONew.setFinishValue(biaozhunCountDTO.getYesterdayCount());
                           shopBiaozhunDO.setFinishValue(biaozhunCountDTO.getYesterdayCount());
                       }
                   }
               }
                   /*  if(todayCountDTOS!=null && todayCountDTOS.size()>0) {
                         for (BiaozhunCountDTO biaozhunCountDTO : todayCountDTOS) {
                             if (shopBiaozhunDO.getId().intValue() == biaozhunCountDTO.getBiaozhunId()) {
                                 if(biaozhunCountDTO.getTodayCount()!=null)
                                 shopBiaozhunDONew.setTodayFinish(biaozhunCountDTO.getTodayCount());
                             }
                         }
                     }*/

               if (biaozhunList != null && biaozhunList.size() > 0) {
                   for (ShopBiaozhunLogDO biaozhunCountDTO : biaozhunList) {
                       if (shopBiaozhunDO.getId().intValue() == biaozhunCountDTO.getBiaozhunId()) {
                           if (biaozhunCountDTO.getToday_count() != null)
                               shopBiaozhunDONew.setTodayFinish(biaozhunCountDTO.getToday_count());
                           shopBiaozhunDO.setTodayFinish(biaozhunCountDTO.getToday_count());

                       }
                   }
               }
               biaozhunDTOSNew.add(shopBiaozhunDONew);
           }
           shopBiaozhunMapper.batchUpdate(biaozhunDTOSNew);
       }

       //计算完成度
       if (biaozhunDTOS != null && biaozhunDTOS.size() > 0) {
           UserShopDO userShopDO = shopMapper.selectById(spuDTO.getShopId());
           Float finishInfo = 0f;
           Float allInfo = 0f;

           for (ShopBiaozhunDO shopBiaozhunDO : biaozhunDTOS) {
               if(shopBiaozhunDO.getFinishValue()==null){
                   shopBiaozhunDO.setFinishValue(0f);
               }
               if(shopBiaozhunDO.getTodayFinish()==null){
                   shopBiaozhunDO.setTodayFinish(0f);
               }
               //allInfo = add(String.valueOf(allInfo), String.valueOf(shopBiaozhunDO.getGongcheng_count()));
               Float biaozhunFinish = add(String.valueOf(shopBiaozhunDO.getFinishValue()), String.valueOf(shopBiaozhunDO.getTodayFinish()));
               Float jine=mul(String.valueOf(biaozhunFinish),String.valueOf(shopBiaozhunDO.getGongcheng_price()),2);
               finishInfo = add(String.valueOf(finishInfo), String.valueOf(jine));
           }
           Float aa = div(String.valueOf(finishInfo), userShopDO.getMoney(), 2);
           userShopDO.setJindu(aa);
           UserShopDO userShopDOnew = new UserShopDO();
           userShopDOnew.setJindu(aa);
           userShopDOnew.setId(userShopDO.getId());
           shopMapper.updateById(userShopDOnew);
       }
   }

    private void insertSpuImg(LogDTO spuDTO, Long bizId, Date now) {
        List<String> imgList = spuDTO.getImgList();
        if(imgList!=null && imgList.size()>0){
            List<ImgDO> imgDOList = imgList.stream().map(item -> {
                ImgDO imgDO = new ImgDO();
                imgDO.setBizType(BizType.GOODS.getCode());
                imgDO.setBizId(bizId);
                imgDO.setUrl(item);
                imgDO.setGmtCreate(now);
                imgDO.setGmtUpdate(now);
                return imgDO;
            }).collect(Collectors.toList());
            imgMapper.insertImgs(imgDOList);
        }

    }

    @Override
    public Page<LogDTO> list(Long shopId, String shopName,Integer type, Integer page, Integer limit, Long adminId) throws ServiceException {
        List<LogDTO> LogDOS = spuMapper.getSpuDTOList(shopId, shopName, type,(page - 1) * limit, limit);
        Integer count = spuMapper.getSpuDTOListCount(shopId, shopName,type);
        Page<LogDTO> dtoPage = new Page<>(LogDOS, page, limit, count);

        return dtoPage;
    }

    @Override
    public LogDTO detail(Long spuId, Long adminId) throws ServiceException {

        LogDO logDO=spuMapper.selectById(spuId);
        LogDTO spuDTO = new LogDTO();
        BeanUtils.copyProperties(logDO, spuDTO);
        UserShopDO userShopDO=shopMapper.selectById(logDO.getShopId());
        spuDTO.setUserShopDO(userShopDO);
        AdminDO adminDO=adminMapper.selectById(logDO.getAdminId());
        spuDTO.setRealName(adminDO.getRealname());
        spuDTO.setFileList(spuDTO.getFile());
        Wrapper<ShopBiaozhunLogDO> wrapper = new EntityWrapper<ShopBiaozhunLogDO>();
        wrapper.eq("shop_log_id",spuId);
        List<ShopBiaozhunLogDO> ShopBiaozhunLogDOS = shopBiaozhunLogMapper.selectList(wrapper);
        ShopBiaozhunLogDOS.forEach(item -> {
            Gson gson=new Gson();
            List<FileInfo> fileInfoList = gson.fromJson(item.getFile(), new TypeToken<List<FileInfo>>(){}.getType());
            item.setImgsList(fileInfoList);

        });
        spuDTO.setBiaozhunList(ShopBiaozhunLogDOS);
        Wrapper<ShopBiaozhunDO> biaozhunDOWrapper = new EntityWrapper<ShopBiaozhunDO>();
        biaozhunDOWrapper.eq("shop_id",logDO.getShopId());

        List<ShopBiaozhunDO> ShopBiaozhunInfoDOS = shopBiaozhunMapper.selectList(biaozhunDOWrapper);
        spuDTO.setBiaozhunInfoList(ShopBiaozhunInfoDOS);

        /*if(logDO.getImg()!=null && !logDO.getImg().equals("")){
            String[] arr = logDO.getImg().split(",");
            List<String> list = Arrays.asList(arr);
            spuDTO.setImgList(list);
        }*/

        return spuDTO;
    }

    @Override
    public LogDTO logDetail(Long shopId, Integer type, String gmtDay, Long adminId) throws ServiceException {
        EntityWrapper<LogDO> wrapper= new EntityWrapper<LogDO>();
        if(gmtDay==null){
            Date nowDate=new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            gmtDay=df.format(nowDate);
        }
        wrapper.eq("shop_id", shopId).eq("type",type).eq("gmt_day",gmtDay).orderDesc(Arrays.asList(new String[] {"id"}));
        List<LogDO> list=spuMapper.selectList(wrapper);
        LogDO logDO=null;
        LogDTO spuDTO = new LogDTO();

        if(list!=null && list.size()>0){
            logDO=list.get(0);
            BeanUtils.copyProperties(logDO, spuDTO);
            UserShopDO userShopDO=shopMapper.selectById(logDO.getShopId());
            spuDTO.setUserShopDO(userShopDO);
            AdminDO adminDO=adminMapper.selectById(logDO.getAdminId());
            spuDTO.setRealName(adminDO.getRealname());
            //spuDTO.setFileList(spuDTO.getFile());
            Wrapper<ShopBiaozhunLogDO> wrapperBiaozhun = new EntityWrapper<ShopBiaozhunLogDO>();
            wrapperBiaozhun.eq("shop_log_id",logDO.getId());
            List<ShopBiaozhunLogDO> ShopBiaozhunLogDOS = shopBiaozhunLogMapper.selectList(wrapperBiaozhun);
            ShopBiaozhunLogDOS.forEach(item -> {
                Gson gson=new Gson();
                System.out.println("item.file=="+item.getFile());
                if(item.getFile()!=null){
                    List<FileInfo> fileInfoList = gson.fromJson(item.getFile(), new TypeToken<List<FileInfo>>(){}.getType());
                    item.setImgsList(fileInfoList);

                }


                /*ShopBiaozhunDO shopBiaozhunDO=shopBiaozhunMapper.selectById(item.getBiaozhunId());
                Wrapper<ShopBiaozhunDO> wrapperB = new EntityWrapper<ShopBiaozhunDO>();
                wrapperB.eq("gongcheng_pxuhao",shopBiaozhunDO.getGongchengPxuhao());
                wrapperB.eq("shop_id",spuDTO.getShopId());
                List<ShopBiaozhunDO> rangeSon=shopBiaozhunMapper.selectList(wrapperB);
                Wrapper<ShopBiaozhunDO> wrapperP = new EntityWrapper<ShopBiaozhunDO>();
                wrapperP.eq("gongcheng_pxuhao","0");
                wrapperP.eq("shop_id",spuDTO.getShopId());
                List<ShopBiaozhunDO> range=shopBiaozhunMapper.selectList(wrapperP);
                item.setRangeSon(range);
                item.setRange(range);*/
            });
            spuDTO.setBiaozhunList(ShopBiaozhunLogDOS);
            /*if(logDO.getImg()!=null && !logDO.getImg().equals("")){
                String[] arr = logDO.getImg().split(",");
                List<String> listImg = Arrays.asList(arr);
                spuDTO.setImgList(listImg);
            }*/

        }

        return spuDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Long spuId, Long adminId) throws ServiceException {
        if (spuMapper.deleteById(spuId) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.GOODS_NOT_EXIST);
        }
        imgMapper.delete(new EntityWrapper<ImgDO>().eq("biz_id", spuId).eq("biz_type", BizType.GOODS.getCode()));
        return "ok";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String batchDelete(String idsJson, Long adminId) throws ServiceException {
        List<Long> ids = JSONObject.parseArray(idsJson, Long.class);
        if (CollectionUtils.isEmpty(ids)) {
            throw new AdminServiceException(ExceptionDefinition.GOODS_NOT_EXIST);
        }
        if (spuMapper.delete(new EntityWrapper<LogDO>().in("id", ids)) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.GOODS_NOT_EXIST);
        }
        imgMapper.delete(new EntityWrapper<ImgDO>().in("biz_id", ids).eq("biz_type", BizType.GOODS.getCode()));

        return "ok";
    }




    @Override
    @Transactional(rollbackFor = Exception.class)
    public LogDTO freezeOrActivation(Long spuId, Integer status, Long adminId) throws ServiceException {
        LogDO LogDO = spuMapper.selectById(spuId);

        if (LogDO == null) {
            throw new AdminServiceException(ExceptionDefinition.GOODS_NOT_EXIST);
        }

        LogDO.setStatus(status);
        LogDO.setGmtUpdate(new Date());
        if (spuMapper.updateById(LogDO) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.GOODS_UPDATE_SQL_FAILED);
        }

        LogDTO spuDTO = new LogDTO();
        BeanUtils.copyProperties(LogDO, spuDTO);

         return spuDTO;
    }
}

